<template>
  <div>
    <!-- from卡片 -->
    <n-card :bordered="false" class="fromCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset"> </BasicForm>
    </n-card>
    <!-- table卡片 -->
    <n-card :bordered="false" class="tableCard">
      <BasicTable
        :bordered="false"
        :columns="columns"
        :row-key="(row) => row.id"
        ref="actionRef"
        :request="loadDataTable"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="1090"
      >
        <template #tableTitle>
          <n-button type="primary" @click="addInfo" :disabled='!authority.includes("menu_add")'>
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            新建
          </n-button>
        </template>
      </BasicTable>
    </n-card>
    <!-- 添加操作 -->
    <n-modal :show="addModal">
      <n-card style="width: 1000px" title="新增菜单" size="huge" :bordered="false">
        <n-form
          :label-width="80"
          :model="addMenu"
          :rules="rules"
          size="medium"
          ref="formRef"
          label-placement="left"
          label-align="left"
        >
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="菜单中文名" path="name">
                <n-input placeholder="请输入菜单中文名" v-model:value="addMenu.name"  maxlength="50"/>
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="菜单英文名" path="nameEn">
                <n-input placeholder="请输入菜单英文名" v-model:value="addMenu.nameEn" maxlength="50"/>
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="父菜单" path="parentId">
                <n-tree-select
                  :options="parentsOptions"
                  clearable
                  v-model:value="addMenu.parentId"
                />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="菜单链接" path="path">
                <n-input placeholder="请输入菜单链接" v-model:value="addMenu.path" maxlength="30"/>
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="所属系统" path="belongSystem">
                <n-select v-model:value="addMenu.belongSystem" :options="belongSystemOptions" />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="状态" path="status">
                <n-select v-model:value="addMenu.status" :options="menuStateOptions" />
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="优先排序" path="priority">
                <n-input-number v-model:value="addMenu.priority" clearable />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="icon" path="icon">
                <n-input placeholder="icon" v-model:value="addMenu.icon" maxlength="30" />
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="服务标志" path="stdSvcInd">
                <n-input placeholder="stdSvcInd" v-model:value="addMenu.stdSvcInd"  maxlength="64"/>
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="接口标志" path="stdIntfInd">
                <n-input placeholder="stdIntfInd" v-model:value="addMenu.stdIntfInd"  maxlength="64"/>
              </n-form-item>
            </n-gi>
          </n-grid>
        </n-form>
        <template #action>
          <n-space justify="end">
            <n-button type="info" :loading="formBtnLoading" @click="addConfirm">确定</n-button>
            <n-button @click="() => (addModal = false)">取消</n-button>
          </n-space>
        </template>
      </n-card>
    </n-modal>
    <!-- 编辑 -->
    <n-modal :show="updateModal">
      <n-card style="width: 1000px" title="编辑菜单信息" size="huge" :bordered="false">
        <n-form
          :label-width="80"
          :model="updateMenu"
          size="medium"
          ref="formRef"
          label-placement="left"
          label-align="left"
        >
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="菜单中文名" path="name">
                <n-input placeholder="请输入菜单中文名" v-model:value="updateMenu.name"  maxlength="50"/>
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="菜单英文名" path="nameEn">
                <n-input placeholder="请输入菜单英文名" v-model:value="updateMenu.nameEn" maxlength="50"/>
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="父菜单" path="parentId">
                <n-tree-select
                  :options="parentsOptions"
                  clearable
                  v-model:value="updateMenu.parentId"
                />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="状态" path="status">
                <n-select v-model:value="updateMenu.status" :options="menuStateOptions" />
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="排序" path="priority">
                <n-input-number v-model:value="updateMenu.priority" clearable />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="服务标志" path="stdSvcInd">
                <n-input placeholder="stdSvcInd" v-model:value="updateMenu.stdSvcInd" maxlength="64"/>
              </n-form-item>
            </n-gi>
          </n-grid>
           <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="接口标志" path="stdIntfInd">
                <n-input placeholder="stdIntfInd" v-model:value="updateMenu.stdIntfInd" maxlength="64"/>
              </n-form-item>
            </n-gi>
          </n-grid>
        </n-form>
        <template #action>
          <n-space justify="end">
            <n-button type="info" :loading="formBtnLoading" @click="updateConfirm">确定</n-button>
            <n-button @click="() => (updateModal = false)">取消</n-button>
          </n-space>
        </template>
      </n-card>
    </n-modal>
    <!-- 查看操作 -->
    <n-modal :show="viewModal">
      <n-card style="width: 1000px" title="菜单详情" size="huge" :bordered="false">
        <n-form
          :label-width="80"
          :model="viewMenu"
          size="medium"
          ref="formRef"
          label-placement="left"
          label-align="left"
        >
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="菜单中文名" path="name">
                <n-input placeholder="请输入菜单中文名" disabled v-model:value="viewMenu.name" />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="菜单英文名" path="nameEn">
                <n-input placeholder="请输入菜单英文名" disabled v-model:value="viewMenu.nameEn" />
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="父菜单" path="parentId">
                <n-tree-select
                  disabled
                  :options="parentsOptions"
                  clearable
                  v-model:value="viewMenu.parentId"
                />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="菜单链接" path="path">
                <n-input placeholder="请输入菜单链接" disabled v-model:value="viewMenu.path" />
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="优先排序" path="priority">
                <n-input-number disabled v-model:value="viewMenu.priority" clearable />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="icon" path="icon">
                <n-input disabled placeholder="icon" v-model:value="viewMenu.icon" />
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="服务标志" path="stdSvcInd">
                <n-input disabled placeholder="stdSvcInd" v-model:value="viewMenu.stdSvcInd" />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="接口标志" path="stdIntfInd">
                <n-input disabled placeholder="stdIntfInd" v-model:value="viewMenu.stdIntfInd" />
              </n-form-item>
            </n-gi>
          </n-grid>
          <n-grid :cols="2" :x-gap="28" style="margin-bottom: 20px">
            <n-gi span="1">
              <n-form-item label="状态" path="status">
                <n-select v-model:value="viewMenu.status" disabled :options="menuStateOptions" />
              </n-form-item>
            </n-gi>
          </n-grid>
        </n-form>
        <template #action>
          <n-space justify="end">
            <n-button type="info" :loading="formBtnLoading" @click="viewConfirm">确定</n-button>
          </n-space>
        </template>
      </n-card>
    </n-modal>
    <!-- 删除操作 -->
    <n-modal
      v-model:show="delModal"
      :mask-closable="false"
      preset="dialog"
      title="确认"
      @positive-click="deletConfirm"
      @negative-click="deletCancel"
    >
      <h3 style="font-size: 15px; margin-top: 10px; margin-bottom: 10px">你确定要删除这条信息吗</h3>
      <n-space justify="end">
        <n-button @click="deletConfirm" style="background-color: #2d8cf0; color: #fff"
          >确认</n-button
        >
        <n-button @click="deletCancel">取消</n-button>
      </n-space>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { h, reactive, ref, onMounted, provide } from 'vue';
import { useMessage } from 'naive-ui';
import { BasicTable, TableAction } from '@/components/Table';
import { BasicForm, useForm } from '@/components/Formrefund/index';
import { getTableList } from '@/api/table/list';
import { columns } from './columns';
import { PlusOutlined } from '@vicons/antd';
import { useRouter } from 'vue-router';
import { getMenuList } from '@/api/menu/list';
import { viewMenuInfo } from '@/api/menu/view';
import { addMneuInfo } from '@/api/menu/add';
import { updateMenuInfo } from '@/api/menu/update';
import { deleteMenuInfo } from '@/api/menu/delete';
import { findMenuByUserId } from '@/api/menu/findMenuByUserId';
import changeMenu from '../../../utils/changeMenu';
import  formatDate  from '@/utils/timestamp'
import { createStorage } from '@/utils/Storage';
const Storage = createStorage({ storage: localStorage });

let authorityJson = Storage.get('OPERATORLIST')
const authority = JSON.parse(authorityJson)

// 表单查询按钮
function handleSubmit(values: Recordable) {
  reloadTable();
}

// 表单重置按钮
function handleReset(values: Recordable) {
  menuListParm.value.name = ''
  menuListParm.value.nameEn = ''
  menuListParm.value.stdSvcInd = ''
  menuListParm.value.stdIntfInd = ''
  reloadTable();
}

const menuListParm = ref({
  name:'',
  nameEn:'',
  stdSvcInd:'',
  stdIntfInd:'',
  pageNum:1,
  pageSize:10,
})

// 全体菜单列表
const loadDataTable = async (res) => {
  console.log(res);
  menuListParm.value.pageNum = res.page
  menuListParm.value.pageSize = res.pageSize
  let data = await getMenuList(menuListParm.value);
  let datas = {
    list: data.data.body.list,
    page: res.page,
    pageSize: res.pageSize,
    pageCount: Math.ceil(data.data.body.total/res.pageSize),
  };
  console.log(data);
  console.log(datas);
  return datas;
};

const belongSystemOptions = [
  {
    label: '前台',
    value: 0,
  },
  {
    label: '后台',
    value: 1,
  },
];
const menuStateOptions = [
  {
    label: '启用',
    value: 0,
  },
  {
    label: '禁用',
    value: 1,
  },
];

const schemas = [
  {
    field: 'name',
    // labelMessage: '这是一个提示',
    component: 'NInput',
    label: '菜单名称：',
    componentProps: {
      maxlength:"50",
      placeholder: '请输入菜单名称',
      onInput: (e: any) => {
        console.log(e);
        menuListParm.value.name = e
      },
    },
  },
  {
    field: 'nameEn',
    // labelMessage: '这是一个提示',
    component: 'NInput',
    label: '英文名称：',
    componentProps: {
       maxlength:"50",
      placeholder: '请输入菜单英文名称',
      onInput: (e: any) => {
        console.log(e);
        menuListParm.value.nameEn = e
      },
    },
  },
  {
    //  slot: 'statusSlot',
    field: 'stdSvcInd',
    // labelMessage: '这是一个提示',
    component: 'NInput',
    label: '标准服务标识：',
    componentProps: {
       maxlength:"64",
      placeholder: '请输入标准服务标识',
      onInput: (e: any) => {
        console.log(e);
        menuListParm.value.stdSvcInd = e
      },
    },
  },
  {
    //  slot: 'statusSlot',
    field: 'stdIntfInd',
    // labelMessage: '这是一个提示',
    component: 'NInput',
    label: '标准接口标识：',
    componentProps: {
       maxlength:"64",
      placeholder: '请输入标准接口标识',
      onInput: (e: any) => {
        console.log(e);
        menuListParm.value.stdIntfInd = e
      },
    },
  },
];

const viewModal = ref(false);
const addModal = ref(false);
const router = useRouter();
const formRef: any = ref(null);
const message = useMessage();
const actionRef = ref();
const delModal = ref(false);
const formBtnLoading = ref(false);
const updateModal = ref(false);

// 列表行为
const actionColumn = reactive({
  width: 220,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction as any, {
      style: 'button',
      actions: [
        {
          label: '编辑',
          text: true,
          color: '#2d8cf0',
          onClick: editInfo.bind(null, record),
          ifShow: () => {
            return authority.includes("menu_update")
          },
        },
        {
          label: '查看',
          text: true,
          color: '#2d8cf0',
          onClick: viewInfo.bind(null, record),
          ifShow: () => {
            return authority.includes("menu_view")
          },
        },
        {
          label: '删除',
          text: true,
          color: '#ff4949',
          onClick: deletInfo.bind(null, record),
          ifShow: () => {
            return authority.includes("menu_delete")
          },
        },
      ],
      select: (key) => {
        message.info(`您点击了，${key} 按钮`);
      },
    });
  },
});

const [register, {}] = useForm({
  gridProps: { cols: '2 s:1 m:2 l:4 xl:4 2xl:4' ,},
  labelWidth: 120,
  // x-gap:80,
  schemas,
});

function onCheckedRow(rowKeys) {
  console.log(rowKeys);
}

function reloadTable() {
  actionRef.value.reload();
}


// 添加菜单信息
const parentsOptions = ref();
async function addInfo() {
  let userId = Storage.get('userId');
  let data = await findMenuByUserId({userId});
  console.log(data);
  parentsOptions.value = changeMenu(data.data.body.menuDto);
  console.log(parentsOptions);
  addModal.value = true;
  message.info('点击了添加');
}

// 添加菜单变为响应式
const addMenu = ref({
  name: '',
  nameEn: '',
  path: '',
  parentId: '',
  belongSystem: '',
  status: '',
  priority: '',
  stdSvcInd: '',
  stdIntfInd: '',
  icon: '',
});

// 添加菜单表单验证规则
const rules = {
  name: {
    required: true,
    validator(rule, value) {
      if (!value) {
        return new Error('请输入菜单中文名');
      } else {
        return true;
      }
    },
    message: '请输入菜单中文名',
    trigger: 'blur',
  },
  nameEn: {
    required: true,
    message: '请输入菜单英文名',
    trigger: 'blur',
  },
  path: {
    required: true,
    message: '请输入菜单链接',
    trigger: 'blur',
  },
};

// 确认添加菜单按钮
const addConfirm = async (e) => {
  console.log(addMenu);
  formRef.value.validate(async (errors) => {
    console.log(addMenu.value);
    if (!errors) {
      console.log(addMenu.value);
      const data = await addMneuInfo(addMenu.value).then((res) => {
        console.log(res);
        message.success('添加成功');
        reloadTable();
      });
      addModal.value = false;
    } else {
      message.error('添加失败');
    }
  });
};

// 编辑
const updateMenu = ref({
  name: '',
  nameEn: '',
  parentId: '',
  status: '',
  priority: '',
  stdSvcInd: '',
  stdIntfInd: '',
});

// 编辑菜单信息
async function editInfo(record: Recordable) {
  console.log(record.menuId);
  let menuId = record.menuId;
  let data = await viewMenuInfo({ menuId });
  // 父菜单
  
  let userId = Storage.get('userId');
  let dataa = await findMenuByUserId({userId});
  console.log(dataa);
  parentsOptions.value = changeMenu(dataa.data.body.menuDto);
  updateMenu.value = data.data.body;
  if(updateMenu.value.status == '0'){
    updateMenu.value.status = '启用'
  }else{
    updateMenu.value.status = '禁用'
  }
  updateModal.value = true;
}

// 确认修改
async function updateConfirm() {
  const data = await updateMenuInfo(updateMenu.value).then((res) => {
    console.log(res);
    message.success('添加成功');
    reloadTable();
     updateModal.value = false;
  });
}

// 查看菜单信息
const viewMenu = ref({});
async function viewInfo(record: Recordable) {
  console.log(record.menuId);
  let menuId = record.menuId;
  let data = await viewMenuInfo({ menuId });
  console.log(data);
  viewMenu.value = data.data.body;
  if (viewMenu.value.status == '0') {
    viewMenu.value.status = '状态1'
  }else if (viewMenu.value.status == '1') {
    viewMenu.value.status = '状态2'
  }
  viewModal.value = true;
}

// 关闭查看模态框
function viewConfirm() {
  viewModal.value = false;
}
// 删除菜单信息
function deletInfo(record: Recordable) {
  console.log('点击了删除', record);
  localStorage.setItem('record', JSON.stringify(record));
  message.info('点击了删除');
  delModal.value = true;
}

// 确认删除
async function deletConfirm() {
  const deleteRole = JSON.parse(localStorage.getItem('record'));
  console.log(deleteRole);
  let { menuId } = deleteRole;
  let data = await deleteMenuInfo({ menuId });
  console.log(data);
  message.success('删除成功');
  delModal.value = false;
  reloadTable();
}

// 取消删除
function deletCancel() {
  message.success('未删除');
  delModal.value = false;
}
</script>

<style lang="less" scoped>
.fromCard {
  margin-top: 12px;
  border: 1px solid rgb(226, 229, 229);
  margin-bottom: 8px;
}
.tableCard {
  border: 1px solid rgb(226, 229, 229);
}
.discount {
  font-size: 18px;
  margin-bottom: 20px;
}
// .n-form-item-label{
//   text-align: right!important;
// }
</style>